import { Component } from 'react'
import store from '../store'
import { GET_NEWS } from '../store/actionType'
import { getNewsList } from '../api'

export default class News extends Component {
	constructor(props) {
		super(props)
		this.state = { news: [] }
	}

	componentDidMount() {
		this.getSelfNewsList()
	}

	getSelfNewsList = async () => {
		const news = await getNewsList()
		this.setState({ news })
	}

	getStoreNewsList = () => {
		const { news } = store.getState()
		this.setState({ news })
	}

	updateStoreNewsList = async () => {
		const { news } = this.state
		store.dispatch({ type: GET_NEWS, news })
	}

	render() {
		return (
			<div>
				<button onClick={() => this.getSelfNewsList()}>
					更新组件内news
				</button>
				&nbsp;
				<button onClick={() => this.getStoreNewsList()}>
					获取store中news
				</button>
				&nbsp;
				<button onClick={() => this.updateStoreNewsList()}>
					同步到store中news
				</button>
				{this.state.news.map((o, i) => (
					<div key={i}>
						<span>{o.name}</span>
						<span>{o.id}</span>
					</div>
				))}
			</div>
		)
	}
}
